import sqlite3
import datetime

# 修复后的交易记录监控工具
def monitor_trade_records():
    print(f"监控时间: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    
    try:
        # 连接到数据库
        conn = sqlite3.connect('trade_monitor.db')
        cursor = conn.cursor()
        
        # 查询总记录数
        cursor.execute("SELECT COUNT(*) FROM trade_records")
        total_count = cursor.fetchone()[0]
        print(f"总记录数: {total_count}")
        
        # 查询今日新增记录数
        today = datetime.date.today().strftime('%Y-%m-%d')
        cursor.execute("SELECT COUNT(*) FROM trade_records WHERE timestamp LIKE ?", (f"{today}%",))
        today_count = cursor.fetchone()[0]
        print(f"今日新增记录数: {today_count}")
        
        # 如果今日没有新增记录，发出警告
        if today_count == 0:
            print("警告: 今日没有新增交易记录！请检查程序是否正常运行。")
        
        # 查询最新5条记录
        print("\n最新5条交易记录:")
        cursor.execute("SELECT * FROM trade_records ORDER BY id DESC LIMIT 5")
        latest_records = cursor.fetchall()
        
        if latest_records:
            # 打印表头
            headers = [desc[0] for desc in cursor.description]
            print(" | ".join(headers))
            print("-" * 100)
            
            # 打印记录
            for record in latest_records:
                print(" | ".join(str(field) for field in record))
        else:
            print("暂无交易记录")
            
        # 检查表结构
        print("\n数据库表结构:")
        cursor.execute("PRAGMA table_info(trade_records)")
        columns = cursor.fetchall()
        for col in columns:
            print(f"  {col[1]} ({col[2]}){' [PRIMARY KEY]' if col[5] else ''}")
        
        # 查询旧表数据（如果有）
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='trade_records_old';")
        if cursor.fetchone() is not None:
            cursor.execute("SELECT COUNT(*) FROM trade_records_old")
            old_count = cursor.fetchone()[0]
            print(f"\n旧表(trade_records_old)记录数: {old_count}")
            print("注意: 旧表数据已保留，需要时可手动迁移")
            
    except Exception as e:
        print(f"监控过程中出错: {str(e)}")
        # 打印错误详情，帮助排查问题
        import traceback
        traceback.print_exc()
    finally:
        # 关闭连接
        if conn:
            conn.close()
            
    # 提供操作建议
    print("\n操作建议:")
    print("1. 确保程序中使用了correct_insert_function.py中的正确函数实现")
    print("2. 运行主程序并观察交易记录是否正常录入")
    print("3. 定期使用此工具检查数据库状态")

if __name__ == "__main__":
    print("=== 交易记录监控工具（已修复）===")
    monitor_trade_records()